package com.solo.system.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.solo.common.core.base.service.impl.BasicServiceImpl;
import com.solo.common.core.utils.collection.CollUtils;
import com.solo.system.api.entity.SysUserPost;
import com.solo.system.mapper.SysPostMapper;
import com.solo.system.mapper.SysUserPostMapper;
import com.solo.system.model.user.SysUserPostConvert;
import com.solo.system.model.user.req.AssignPostReq;
import com.solo.system.model.user.resp.UserPostResp;
import com.solo.system.service.SysUserPostService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * 用户岗位 Service实现类
 * @author 十一
 * @since 2024-02-20 14:42
 * 人生若只如初见，何事秋风悲画扇
 **/
@Service
@RequiredArgsConstructor
public class SysUserPostServiceImpl extends BasicServiceImpl<SysUserPostMapper, SysUserPost> implements SysUserPostService {

    private final SysPostMapper sysPostMapper;
    private final SysUserPostMapper sysUserPostMapper;
    
    @Override
    public UserPostResp queryUserPost(Long userId) {
        // 获取全部的岗位信息
        List<UserPostResp.PostInfo> roleInfos = QueryChain.of(this.sysPostMapper)
                .listAs(UserPostResp.PostInfo.class);
        
        // 获取用户下所属的岗位id集合
        List<Long> postIds = sysUserPostMapper.selectPostIdsByUserId(userId);

        // 构造用户岗位信息
        UserPostResp resp = new UserPostResp();
        resp.setPostInfos(roleInfos);
        resp.setSelectIds(postIds);
        return resp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean assignPost(AssignPostReq req) {
        // 删除旧的用户岗位关联
        sysUserPostMapper.deleteByUserIds(Collections.singleton(req.getUserId()));

        Set<Long> ids = req.getPostIds();
        if (CollUtils.isEmpty(ids)) {
            return Boolean.TRUE;
        }
        // 批量保存新的用户岗位关联
        return saveBatch(SysUserPostConvert.INSTANCE.convert(req));
    }

}
